package basic50.thirtieth;

import java.util.Arrays;
import java.util.Scanner;

public class Basic30 {
    public static void main(String[] args) {
        //题目：有一个已经排好序的数组。现输入一个数，要求按原来的规律将它插入数组中。
      //  程序分析：首先判断此数是否大于最后一个数，然后再考虑插入中间的数的情况，插入后此元素之后的数，依次后移一个位置。
        int[] a = {1,3,5,6,8,9,10,22,55,0};
        arr(a);
        System.out.println("========");
        int[] b = {99,88,77,66,55,44,33,22,11,0};
        arr(b);
    }

    private static void arr(int[] a) {
        System.out.println(Arrays.toString(a));
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter  numbers: ");
        int n = sc.nextInt();
        if(a[a.length-2] > a[a.length-3]){
            asc(a,n);
        }else {
            des(a,n);
        }
    }

    private static void des(int[] a,int n) {
        if(n < a[a.length-2]){
            a[a.length-1]=n;
            System.out.println(Arrays.toString(a));
        }else {
            for (int i = a.length -1; i > 0; i--) {
                if(n > a[i-1]){
                    a[i] =a[i-1];
                }else {
                    a[i]=n;
                    break;
                }
            }
            System.out.println(Arrays.toString(a));
        }
    }

    private static void asc(int[] a,int n) {
        if(n > a[a.length-2]){
            a[a.length-1]=n;
            System.out.println(Arrays.toString(a));
        }else {
            for (int i = a.length -1; i > 0; i--) {
                if(n < a[i-1]){
                    a[i] =a[i-1];
                }else {
                    a[i]=n;
                    break;
                }
            }
            System.out.println(Arrays.toString(a));
        }
    }
}
